/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelBiseccion.java
 *
 * Created on 11-oct-2010, 14:12:47
 */
package interfaz.FuncionPanels;

//import java.awt.FlowLayout;
//import javax.print.DocFlavor.STRING;
//import javax.management.monitor.GaugeMonitor;
import interfaz.NuMethodApp;
import interfaz.PanelMain;
import java.awt.Color;
import java.util.Locale;
import javax.swing.JFrame;
//import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import metodos.inpol.InterpolacionLagrange;
import metodos.inpol.Polinomio;

//import javax.swing.table.TableModel;
//import org.jdesktop.swingx.JXTable;
/**
 *
 * @author The NuMethod Team
 */
public class PanelLagrange extends javax.swing.JPanel {

    private static NuMethodApp parent;

    /** Creates new form PanelBiseccion */
    public PanelLagrange(NuMethodApp parent) {
        initComponents();
        initComponents2();

        this.parent = parent;
    }

    public void setlinksColor(Color c) {
        jXHyperlink1.setClickedColor(c);
        jXHyperlink1.setUnclickedColor(c);

    }

    private void initComponents2() {
        //this.jTable1.setVisible(false);
        TablePuntos.setEditable(true);
        TablePuntos.setShowGrid(true);
        TablePuntos.setOpaque(true);
        TablePuntos.setAutoStartEditOnKeyStroke(true);
        TablePuntos.setRolloverEnabled(true);
        TablePuntos.setSurrendersFocusOnKeystroke(true);
        TablePuntos.setTerminateEditOnFocusLost(true);
        TablePuntos.setFillsViewportHeight(true);
        TablePuntos.setEditable(false);


//        TableA.setAutoResizeMode(JXTable.AUTO_RESIZE_LAST_COLUMN);
//        TableB.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
//        TableX.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
        TablePuntos.setVisibleColumnCount(0);

        rebuildTableModels(3);


    }

    /**
     * Este metodo devuelve los valores existentes en las tablas a dos variables
     * <br>Pasadas como parametro.
     * 
     * <p>
     * WARNING: esta version hasta ahora no soporta variables distintas a numeros<br>
     * asi que se debe de tener cuidado de no ingresar ningun valor que no sea numerico en las tablas.
     * @param A
     * @param B
     */
    /**
     * Metodo que reconstruye de forma dinamica los modelos de tabla
     * luego de cada entrada de datos
     * @param a
     */
    public void updateTableModels() {
        //COnfigurar los modelos de tabla para las 3 tablas disponibles.
        DefaultTableModel m = PanelInterpolacion.getMa();
        this.TablePuntos.setModel(m);


        m.fireTableDataChanged();
    }

    public void rebuildTableModels(Integer a) {
        //Constuir el modelo para la tabla A
        Double[][] test = new Double[2][a];
        String[] names = new String[a];

        for (int i = 0; i < a; i++) {
            String aTest = "X" + (i + 1);
            names[i] = aTest;
        }

        //Constuir el modelo para la tabla B
        Double[][] testB = new Double[a][1];
        String[] namesB = new String[1];

        for (int i = 0; i < 1; i++) {
            String aTest = "B" + (i + 1);
            namesB[i] = aTest;
        }

        //Construir el Modelo para la tabla X
        Double[][] testX = new Double[1][a];
        String[] namesX = new String[a];


        for (int i = 0; i < a; i++) {
            String aTest = "X" + (i + 1);
            namesX[i] = aTest;
        }

        //COnfigurar los modelos de tabla para las 3 tablas disponibles.
        DefaultTableModel m = PanelInterpolacion.getMa();
        this.TablePuntos.setModel(m);


        m.fireTableDataChanged();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TablePuntos = new org.jdesktop.swingx.JXTable();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jXHyperlink1 = new org.jdesktop.swingx.JXHyperlink();
        btnEjecutar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblCoeficientes = new javax.swing.JTable();
        lblValor = new javax.swing.JLabel();
        txtValor = new javax.swing.JTextField();
        LabelGrandote = new javax.swing.JLabel();
        LabelGrandote2 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        setToolTipText("Polinomio de Lagrange");

        TablePuntos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(TablePuntos);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/help.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("Puntos");

        jLabel1.setText("Metodo de Lagrange");

        jLabel2.setText("Cuidado: Los puntos solo pueden ser cambiados desde el panel de entrada");

        jXHyperlink1.setText("Ir al panel de entrada");
        jXHyperlink1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jXHyperlink1ActionPerformed(evt);
            }
        });

        btnEjecutar.setText("Ejecutar");
        btnEjecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEjecutarActionPerformed(evt);
            }
        });

        tblCoeficientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tblCoeficientes);

        lblValor.setText("Valor evaluado en el punto:");

        LabelGrandote2.setText("jLabel3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4))
                        .addGap(478, 478, 478)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnEjecutar)
                            .addComponent(jXHyperlink1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18))
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(lblValor)
                .addGap(49, 49, 49)
                .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(163, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LabelGrandote)
                .addContainerGap(626, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(LabelGrandote2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(2, 2, 2)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jXHyperlink1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnEjecutar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblValor)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(43, 43, 43)
                .addComponent(LabelGrandote2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(LabelGrandote)
                .addGap(85, 85, 85))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        NuMethodApp.helpLauncher("Lagrange.html");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jXHyperlink1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXHyperlink1ActionPerformed
        parent.getPanelMain().cardChanger(PanelMain.INTERPOLACION);
    }//GEN-LAST:event_jXHyperlink1ActionPerformed

    private void btnEjecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEjecutarActionPerformed
        double[] x = new double[TablePuntos.getModel().getColumnCount()];
        double[] fx = new double[TablePuntos.getModel().getColumnCount()];

        for (int i = 0; i < x.length; i++) {
            x[i] = Double.parseDouble((String) TablePuntos.getModel().getValueAt(0, i));
            fx[i] = Double.parseDouble((String) TablePuntos.getModel().getValueAt(1, i));
        }

        double val = PanelInterpolacion.getValue();

        Polinomio[] L = InterpolacionLagrange.getCoeficientes(x);

        StringBuilder grandote = new StringBuilder();
        grandote.append("p(x) = ");
        String[][] newModel = new String[L.length][1];
        for (int i = 0; i < L.length; i++) {
            StringBuilder s = new StringBuilder();
            s.append("L").append(i).append("(X) = ");
            s.append(L[i].getCoeficientes()[L.length - 1]).append("x^").append(L.length - 1);
            for (int j = L.length - 2; j >= 1; j--) {
                s.append(" + ");
                s.append(L[i].getCoeficientes()[j]).append("x^").append(j);
            }
            s.append(" + ").append(L[i].getCoeficientes()[0]);
            newModel[i][0] = s.toString();
                    grandote.append("L").append(i).append("(X)*").append(fx[i]).append(" + ");

        }
        String[] names = {"Li(X)"};

        grandote.append(0);
        LabelGrandote2.setText("El polinomio de Lagrange que interpola los puntos dados es:");
        LabelGrandote.setText(grandote.toString());

        DefaultTableModel dt = new DefaultTableModel(newModel, names);

        tblCoeficientes.setModel(dt);
        dt.fireTableDataChanged();

        double evalX = InterpolacionLagrange.solucionar(L, fx, val);

        txtValor.setText("" + evalX);
    }//GEN-LAST:event_btnEjecutarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel LabelGrandote;
    private javax.swing.JLabel LabelGrandote2;
    private org.jdesktop.swingx.JXTable TablePuntos;
    private javax.swing.JButton btnEjecutar;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.swingx.JXHyperlink jXHyperlink1;
    private javax.swing.JLabel lblValor;
    private javax.swing.JTable tblCoeficientes;
    private javax.swing.JTextField txtValor;
    // End of variables declaration//GEN-END:variables
}
